/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.risk.controller;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.bean.SourceQueryBean;
import com.koron.risk.domain.LocalHazardSource;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.risk.service.api.LocalHazardSourceService;
import com.koron.risk.util.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "LocalHazardSource", description = "危险源管理")
@RestController
@RequestMapping("/LocalHazardSource")
public class LocalHazardSourceController {
    private static final Logger logger = LoggerFactory.getLogger(LocalHazardSourceController.class);
    @Autowired
    LocalHazardSourceService service;

    @Autowired
    CorpManagementService corpService;

    @ApiOperation("获取危险源详情")
    @ApiImplicitParam(name = "id", value = "危险源id" , paramType = "query", dataType = "String")
    @RequestMapping(value = "/getDetails.htm", method = {RequestMethod.GET})
    public MessageBean<?> getDetails(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        return service.getDetails("local_hazard_source", "local_risk", id);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "危险源名称" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "businessTypeId", value = "业态" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "hazardTypeId", value = "类型" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "riskLevelStart", value = "风险等级" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "riskLevelEnd", value = "风险等级" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "state", value = "状态" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "important", value = "重大危险源：0否,1是" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "exclusive", value = "专属危险源：0否,1是" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "disposalState", value = "专有危险源是否处理，扩充到标准库,0:未处理,1:已导出,2:已处理" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "page", value = "当前页" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "keyword", value = "关键词" , paramType = "query", dataType = "String")})
    @ApiOperation("危险源台账")
    @RequestMapping(value = "/list.htm", method = {RequestMethod.GET})
    public MessageBean<?> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore SourceQueryBean queryBean) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        return service.list(queryBean);
    }

    @ApiOperation("提交操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "note", value = "说明" , paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/submitSourceAndRisk.htm", method = {RequestMethod.POST})
    @Log(title = "新增、修改危险源提交操作",businessModule = "专属危险源", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> submitSourceAndRisk(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody List<LocalHazardSource> lhsList, String title, String note, String approvalCode) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        MessageBean<?> msg = service.submit(lhsList, user, title, note, approvalCode);
        return msg;
    }


    @ApiOperation("废弃危险源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "note", value = "说明" , paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/discard.htm", method = {RequestMethod.POST})
    @Log(title = "废弃本地危险源", businessModule = "专属危险源", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<?> discard(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(value = "idList") List<String> idList, String title, String note, String approvalCode) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        MessageBean<?> msg = service.discard(idList, user, title, note, approvalCode);
        return msg;
    }


    @ApiOperation("危险源导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "title", value = "标题" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "note", value = "说明" , paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/improtExcel.htm", method = {RequestMethod.POST})
    @Log(title = "导入本地危险源", businessModule = "专属危险源", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> improtExcel(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                      MultipartFile file, String title, String note, String corpCode, String approvalCode) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        return service.importFromExcel(user, file, title, note, corpCode, approvalCode);
//        return service.importFromExcelOnThread(user, file, title, note, corpCode, approvalCode);
    }

    @ApiOperation("保存草稿")
    @RequestMapping(value = "/saveDraft.htm", method = {RequestMethod.POST})
    @Log(title = "新增、修改本地危险源保存草稿", businessModule = "专属危险源", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> saveDraft(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody List<LocalHazardSource> lhsList) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        MessageBean<?> msg = service.saveDraft(lhsList, user);
        return msg;
    }

    @ApiOperation("下载模板")
    @RequestMapping(value = "/exportExcelTemplate.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exportExcelTemplate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        File targetFile = new File("static/excel/LocalHazardSourceTemplate.xlsx");
        try {
            InputStream initialStream = getClass().getClassLoader().getResourceAsStream("static/excel/LocalHazardSourceTemplate.xlsx");
            FileUtils.copyInputStreamToFile(initialStream, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("危险源模板", targetFile, "default.btl", map);
    }

    @SuppressWarnings("rawtypes")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "危险源名称" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "businessTypeId", value = "业态" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "hazardTypeId", value = "类型" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "状态" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "important", value = "重大危险源：0否,1是" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "exclusive", value = "专属危险源：0否,1是" , paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "disposalState", value = "专有危险源是否处理，扩充到标准库,0:未处理,1:已导出,2:已处理" , paramType = "query", dataType = "Integer")})
    @ApiOperation("导出")
    @RequestMapping(value = "/exportList.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exportList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore SourceQueryBean queryBean) {
        if (null == user) {
            return null;
        }
        queryBean.setPage(null);
        queryBean.setPageSize(null);
        String corpCode = queryBean.getCorpCode();
        queryBean.setCorpCode("('"+corpCode+"')");
        MessageBean<?> msg = service.exportList(queryBean);
        if (msg.getData() == null) {
            return null;
        }
        if (StringUtils.isEmpty(corpCode)) {
            return null;
        }
        MessageBean<?> corpMsg = corpService.getOne(corpCode);
        if (corpMsg.getCode() != 0) {
            return null;
        }
        CorpBean corpBean = (CorpBean) corpMsg.getData();
        if (corpBean == null) {
            return null;
        }
        File targetFile = new File("static/excel/LocalHazardSource.xlsx");
        try {
            InputStream initialStream = getClass().getClassLoader().getResourceAsStream("static/excel/LocalHazardSource.xlsx");
            FileUtils.copyInputStreamToFile(initialStream, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        DataBean data = (DataBean) msg.getData();
        Map<String, Object> map = new HashMap<>();
        map.put("data", data.getList());
        return Excel.createFile(corpBean.getCorpName() + "危险源台账", targetFile, "LocalHazardSource.btl", map);
    }

    @ApiOperation("历史版本")
    @ApiImplicitParam(name = "code", value = "危险源code", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getHistoryList.htm", method = {RequestMethod.GET})
    public MessageBean<?> getHistoryList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String code) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        return service.getHistoryList(code);
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        return service.getProcessData(ids);
    }

    @ApiOperation("删除草稿")
    @ApiImplicitParam(name = "id", value = "id" , paramType = "query", dataType = "String")
    @RequestMapping(value = "/deleteDraft.htm", method = {RequestMethod.GET})
    public MessageBean<?> deleteDraft(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        if (null == user) {
            MessageBean<CorpBean> msg = new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        return service.deleteDraft(id);
    }
}
